#!/usr/bin/python
# -*- coding:utf-8 -*-
# @Time  : 6/15/20
# @Author: yanlh
# @usage : 不要在同一主机上保留大量无用容器
import docker_utils
import sys

sys.path.append('..')
from common_utils import CBBCommonUtils


def get_plugin_info():
    plugin_info = {
        "name": "Docker_operate_001 Swarm",
        "plugin_id": "Docker_operate_001",
        "plugin_type": "Docker_Operate_Safe",
        "info": "Ensure that container sprawl is avoided.",
        "level": "B",
        "module": "Safety reinforcement",
        "author": "yanlh",
        "keyword": "Safety reinforcement",
        "configable": "false",
    }
    return plugin_info


logger = None
cur_user = None
cur_module = None
cur_task = None
path = None


def set_plugin_logger(setter, user, module, task, *args, **kwargs):
    global logger, cur_user, cur_module, cur_task
    logger = setter
    cur_user = user
    cur_module = module
    cur_task = task


def single_logger_record(level, des, module='_Scan'):
    if level == 'error':
        logger.debug_error(cur_user, cur_module, cur_task + module, '', des)
    if level == 'info':
        logger.debug_info(cur_user, cur_module, cur_task + module, '', des)
    if level == 'warning':
        logger.debug_warning(cur_user, cur_module, cur_task + module, '', des)


def scan_operate_config(func_args):
    cmd = "docker info --format '{{.Containers}}:{{.ContainersRunning}}'"
    result, output = CBBCommonUtils.cbb_run_cmd(func_args['ip'], cmd, username=func_args['username'],
                                                passwd=func_args['passwd'])
    if result:
        des = "CMD process ERROR. Error info: {}".format(result)
        single_logger_record('error', des)
        return [des], 1
    value = (''.join(output)).split(':')
    total = value[0].strip() if value[0] else 0
    running = value[1].strip() if value[1] else 0
    diff = int(total) - int(running)
    if diff > 25:
        des = 'Not Safe. The host keeps a large number of containers.'
        single_logger_record('warning', des)
        return [des], 1
    des = 'Safe. The host do not keep a large number of containers.'
    single_logger_record('info', des)
    return [des], 0


# 扫描函数
def scan(func_args, flag=0):
    single_logger_record('info', "Scan Start.")
    scan_list, error_count = scan_operate_config(func_args)
    scan_list.append('Scan Complete')
    single_logger_record('info', 'Scan Complete')
    if flag:
        info = ['Please check and config the unsafe item manually.', 'Reinforce Complete.']
        single_logger_record('info', "Reinforce Complete.", '_Reinforce')
        scan_list.extend(info)
        return scan_list, error_count
    return scan_list, error_count


# 回滚函数
def rollback(func_args):
    des_list = ["This function don't need to rollback.", 'Rollback Complete.']
    single_logger_record('info', "Rollback Complete.", '_Rollback')
    return des_list, 0


def check(ip, *args, **kwargs):
    sys_user = kwargs.get("system_user")
    sys_pwd = kwargs.get("system_pwd")
    comm = kwargs.get("command")
    try:
        single_logger_record('info', "docker_swarm_001 Start.", '_Check')
        func_args = {'ip': ip, 'username': sys_user, 'passwd': sys_pwd, 'comm': comm}
        result = docker_utils.check_func(scan, rollback, func_args)
        single_logger_record('info', "docker_swarm_001 Complete.", '_Check')
        return result
    except Exception as er:
        code = 1
        des = ["ERROR:", str(er)]
        single_logger_record('error', des, '_Check')
        return {"code": code, "count": 0, "des": des}


if __name__ == '__main__':
    """
    本地测试
    """
    check(ip=None, command=1)
